#coding=utf-8
import sys

from uliweb.orm import get_model, set_dispatch_send, Begin, Commit, Rollback

set_dispatch_send(False)

log = open('log.txt', 'w')

def call(args, options, global_options):
    from uliweb.core.SimpleFrame import get_apps, get_app_dir, Dispatcher

    app = Dispatcher(apps_dir=global_options.apps_dir, start=False)
    try:
        Begin()
        try:
            process(args, options, global_options)
            Commit()
        except:
            Rollback()
            import traceback
            traceback.print_exc()
    finally:
        log.close()
        
def process(args, options, global_options):
    from sqlalchemy.sql import func
    from uliweb import settings
    
    D = get_model('planexecutedetails')
    P = get_model('planexecute')
    
    D.modified_user.auto = False
    
    n = 0
    d_n = 0
    for d in D.all(D.c.planexecute==None):
        row = P.get((P.c.task==d._task_) & (P.c.plan==d._plan_) & (P.c.system==d._system_))
        if row:
            d.planexecute = row.id
            d.save()
            n += 1
        else:
            d.delete()
            d_n += 1
        
    print 'Totoal: %d, Deleted: %d' % (n, d_n)